<template>
  <div class="login-parent">
    <div class="login-box">
      <div class="title">
        <span>博客</span>
        <span> | </span>
        <span>后台</span>
      </div>
      <div class="login-form">
        <el-form v-model="loginForm">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名..."
                      :prefix-icon="User" autofocus/>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" placeholder="请输入密码..."
                      :prefix-icon="Lock" type="password" show-password/>
          </el-form-item>
          <el-form-item prop="code">
            <el-input v-model="loginForm.code" placeholder="请输入验证码..."
                      :prefix-icon="Key"/>
            <el-image :src="imgUrl" @click="checkImageCode"/>
          </el-form-item>
          <el-form-item prop="rememberMe">
            <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loginHandler">
              <span v-if="loading">登 录</span>
              <span v-else>登 录 中 ...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {User, Lock, Key} from '@element-plus/icons-vue'
import {checkVerify, getVerify, login, loginVo} from "../api/user/user";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter()
const loading = ref<boolean>(true)
const imgUrl = ref<string>('')

const loginForm = reactive<loginVo>({
  username: '',
  password: '',
  code: '',
  rememberMe: false
})

// 登陆处理
const loginHandler = async () => {
  const {data} = await checkVerify(loginForm.code)
  if (data.data === false) {
    ElMessage.error(data.message);
    loginForm.code = ''
    await checkImageCode()
    return
  }
// 登陆请求
  loading.value = false
  login(loginForm).then(res => {
    if (res.data.code === 200) {
      ElMessage.success("登陆成功")
      router.push('/dashboard')
    } else {
      ElMessage.error(res.data.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('系统异常')
  })
  loading.value = true


}

const checkImageCode = async () => {
  const {data} = await getVerify();
  loginForm.code = ''
  imgUrl.value = data.data.imgBase64;
}

onMounted(() => checkImageCode())

</script>

<style scoped lang="scss">
.login-parent {
  width: 100%;
  height: 100%;
  display: flex;
  background-image: url("../assets/images/background-image.jpg");

  .login-box {
    width: 500px;
    height: 350px;
    border-radius: 10px;
    margin: auto;
    background-color: white;
  }
}

</style>